import { useState } from "react";
import { ResizableBox } from "react-resizable";
import "react-resizable/css/styles.css";
import { Transforms } from "slate";
import "./index.less";
import cx from "classNames";
import { useSelected, useSlateStatic, ReactEditor } from "slate-react";

const Image = ({ attributes, children, element }: any) => {
  const [height, setHeight] = useState(100);
  const [width, setWidth] = useState(100);

  const editor = useSlateStatic();
  const path = ReactEditor.findPath(editor, element);
  const selected = useSelected();

  const onResize = (event: any, { node, size, handle }: any) => {
    setHeight(size.height);
    setWidth(size.width);
  };

  const onMouseLeave = (e: any) => {
    e.preventDefault();
    Transforms.setNodes(
      editor,
      {
        ...element,
        width,
        height,
      },
      { at: path }
    );
  };

  return (
    <div {...attributes} data-slate-node='image'  style={{ display: "inline-block" }}  contenteditable={false}>
      {children}
      <div
        style={{ width: width, marginRight: 2 }}
        className="element-img-container"
      >
        {selected ? (
          <div className="resizable-image-handle-border"></div>
        ) : null}
        {selected ? (
          <>
            <span
              className={cx(
                "resizable-image-point",
                "resizable-image-point-top-left"
              )}
            ></span>
            <span
              className={cx(
                "resizable-image-point",
                "resizable-image-point-top-right"
              )}
            ></span>
            <span
              className={cx(
                "resizable-image-point",
                "resizable-image-point-bottom-left"
              )}
            ></span>
            <span
              className={cx(
                "resizable-image-point",
                "resizable-image-point-bottom-right"
              )}
            ></span>
          </>
        ) : null}
        <ResizableBox
          handle={
            <div
              onMouseLeave={onMouseLeave}
              className={"resizable-image-handle"}
              style={{ width: width + 16, height: height + 16 }}
            />
          }
          height={height}
          width={width}
          onResize={onResize}
        >
          <div style={{ width, height }}>
            <img style={{ width, height }} src={element.url} />
          </div>
        </ResizableBox>
      </div>
    </div>
  );
};

export default Image;
